package com.aj.databases.dao;

import java.sql.SQLException;
import java.util.List;

import android.content.Context;

import com.aj.databases.DatabaseHelper;
import com.aj.databases.entry.Account;
import com.aj.databases.entry.User;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.RuntimeExceptionDao;

public class UserDao {
	public RuntimeExceptionDao<User, Integer> dao = null;
	private DatabaseHelper helper = null;
	private Context context;

	public UserDao(Context context) {
		helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
		dao = helper.getRuntimeExceptionDao(User.class);
		this.context = context;
	}

	public User getUserByUserId(String userid) {
		List<User> datas = null;
		try {
			datas = dao.queryBuilder().where().eq(User.USER_ID, userid).query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (datas != null && datas.size() > 0) {
			return datas.get(0);
		} else {
			return null;
		}
	}

	public boolean insertUser(User user) {
		List<User> datas = null;
		try {
			datas = dao.queryBuilder().where()
					.eq(User.USER_ID, user.getUser_id()).query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (datas != null && datas.size() > 0) {
			user.setId(datas.get(0).getId());
			user.setPortrait_path(datas.get(0).getPortrait_path());
			return dao.update(user) > 0;
		} else {
			return dao.createIfNotExists(user) != null;
		}
	}

	public boolean updateUser(User user) {
		return dao.update(user) > 0;
	}

	public User getCurrentUser(String token) {
		AccountDao accountDao = new AccountDao(context);
		Account account = accountDao.getByToken(token);
		if (account != null) {
			return getUserByUserId(account.getLast_used_user_id());
		}
		return null;
	}
}
